var tableAjax = false;

var dtLabelArr = new Array();
dtLabelArr[0] = 'danger';
dtLabelArr[1] = 'success';
dtLabelArr[2] = 'primary';
var notifyIndex = 1;
$c = {
    confirm: function (title, okFunction, cancelFunction) {
        return layer.confirm(title, {
            btn: ['确定', '取消'] //按钮
        }, okFunction, cancelFunction);
    },
    ok: function (title, okFunction) {
        let okDialog = layer.alert(title, {
            skin: 'layui-layer-lan' //样式类名
            , closeBtn: 1
        }, okFunction);
    },
    dialog: function (title, url, width) {
        width = width || '30%';
        return layer.open({
            type: 1,
            title: title,
            area: width, //宽高
            content: "<div class='dialog-box jarviswidget jarviswidget-sortable  '><div><i class='fa fa-refresh fa-spin'></i> 加载中...</div></div>",
            success: function (layero, index) {
                $.ajax({
                    type: 'get',
                    url: url,
                    dataType: 'html',
                    beforeSend: function () {

                    },
                    complete: function () {

                    },
                    success: function (d) {
                        layero.find('.layui-layer-content').html(d);
                        var wHeight = $(window).height();
                        var formHeight = wHeight - 250;
                        layero.find(".form-content").css({'max-height': formHeight});
                        var layerHeight = layero.height();
                        var layerTop = (wHeight - layerHeight) / 2;
                        layero.css({top: layerTop});
                    }
                });
                $("body").css("overflow", "hidden");
            },
            end: function () {
                $("body").css("overflow", "auto");
            },
            resize: false

        });
    },
    label: function (content, flag) {
        flag = flag || 1;
        if (dtLabelArr[flag] == undefined) {
            var classStr = dtLabelArr[0];
        } else {
            var classStr = dtLabelArr[flag];
        }


        var html = '<span class="label label-' + classStr + '">' + content + '</span>';
        return html;
    },
    button: function (name, click, dfClass) {
        let html = '<a class="btn btn-' + dfClass + ' btn-xs" href="javascript:void(0);" onclick="' + click + '">' + name + '</a> ';
        return html;
    },
    dataTools: function (html) {
        $(".DTT").appendTo(html);
    },
    dataTable: function (tbObj, url, columns, options, tools) {
        tableAjax = true;
        var defaultsTools = [{
            'sExtends': 'div',
            'sButtonText': '<i class="fa fa-refresh"></i>',
            "fnClick": function (nButton, oConfig, oFlash) {
                if (!tableAjax)
                    table.fnDraw();
            }
        }];
        if (tools != undefined) {
            var settingTools = $.merge(defaultsTools, tools);
        } else {
            var settingTools = defaultsTools;
        }

        var defaults = {
            bPaginate: true,
            bLengthChange: true,
            bInfo: true,
            bSort: true,
            iDisplayLength: 10,
            oTableTools: {
                'aButtons': settingTools
            },
            aaSorting: [[0, "desc"]],
            fnFooterCallback: function (nFoot, aData, iStart, iEnd, aiDisplay, dFooter) {

            },
            fnRowCallback: function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
            },
        }
        var settings = $.extend(defaults, options);
        /*  $.extend($.fn.dataTableExt.oStdClasses, {
         "sWrapper": "dataTables_wrapper form-inline",
         "sFilterInput": "form-control",
         "sLengthSelect": "form-control"
         });*/
        var table = $("#" + tbObj).dataTable({
            "sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'T><'col-sm-6 col-xs-12 hidden-xs'l>r>" +
                "t" +
                "<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
            "autoWidth": true,
            'bServerSide': true,
            "ajax": url,//指定要从哪个URL获取数据
            "lengthMenu": [10, 25, 50, 100],
            "columns": columns,
            "ordering": false,
            'bPaginate': settings.bPaginate,
            "bSortable": settings.bSort, //排序
            "bInfo": settings.bInfo,
            "language": {
                "lengthMenu": "每页显示 _MENU_ 条",
                "zeroRecords": "找不到数据",
                "info": "从 _START_ 到 _END_ 共 _TOTAL_ 条",
                "infoEmpty": "无记录",
                "infoFiltered": "(filtered from _MAX_ total records)",
                "oPaginate": {"sFirst": "首页", "sLast": "尾页", "sNext": ">", "sPrevious": "<"}
            },
            'oTableTools': settings.oTableTools,
            "initComplete": function (settings, json) {
                tableAjax = false;
            },
            "footerCallback": function (nFoot, aData, iStart, iEnd, aiDisplay, dFooter) {
                settings.fnFooterCallback(nFoot, aData, iStart, iEnd, aiDisplay, dFooter);
            },
            "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                settings.fnRowCallback(nRow, aData, iDisplayIndex, iDisplayIndexFull);
            },

        });
        return table;
    },
    dataTableRefresh: function (dataTableObj, complete) {
        complete = complete || true;
        dataTableObj.fnDraw(complete);
    },
    dataTableSearch: function (dataTableObj, searchForm) {
        // console.log(12321);
        var url = $("#" + searchForm).attr('action');

        if (url.indexOf("?") > 0) {
            searchUrl = url + "&" + $("#" + searchForm).serialize();
        } else {
            searchUrl = url + "?" + $("#" + searchForm).serialize();
        }
        dataTableObj.DataTable().ajax.url(searchUrl).load();
        //
        // dataTableObj.ajafnReloadAjax(searchUrl)();
    },
    notify: function (msg) {
        layer.alert(msg, {
            title: '提示',
        });
    },
    dialogClose: function (dialogIndex) {
        layer.close(dialogIndex);
    },
    ajax: function (options) {
        var defaults = {
            type: 'post',
            dataType: "json",
            beforeSend: function () {
                loadIndex = layer.load(1, {
                    shade: [0.1, '#fff'] //0.1透明度的白色背景
                });//0.1透明度的白色背景);
            }, complete: function () {
                layer.close(loadIndex)
            },
        }
        var settings = $.extend(defaults, options);

        var form = $(options.form);

        $.ajax({
            type: settings.type,
            url: form.attr('action'),
            data: form.serialize(),
            dataType: settings.dataType,
            beforeSend: function () {
                settings.beforeSend();
            },
            complete: function () {
                settings.complete();
            },
            success: options.success
        });
        return false;

    },
    msg: function (content) {
        layer.msg(content);
    },
    dataTableV2: function (tbObj, url, columns) {
        let tableV2 = $("#" + tbObj).dataTable({
            ajax: {
                type: "POST",
                url: url,
            },
            bPaginate: true,
            bLengthChange: true,
            destroy: true,
            bInfo: true,
            bSort: true,
            bRedraw: true,
            bServerSide: true,
            autoWidth: true,
            searching: false,
            columns: columns,
            language: {
                "lengthMenu": "每页显示 _MENU_ 条",
                "zeroRecords": "找不到数据",
                "info": "从 _START_ 到 _END_ 共 _TOTAL_ 条",
                "infoEmpty": "无记录",
                "infoFiltered": "(filtered from _MAX_ total records)",
                "oPaginate": {"sFirst": "首页", "sLast": "尾页", "sNext": "下一页", "sPrevious": "上一页"}
            },
        });
        return tableV2;
    },
    pageGo: function (url) {
        $.ajax({
            type: "GET",
            url: url,
            data: "page=menu",
            dataType: "html",
            beforeSend: function () {
                $("#content").html("");
                $("#content").html('<h1 class="ajax-loading-animation"><i class="fa fa-cog fa-spin"></i> 加载中...</h1>');
                $("body").find("> *").filter(":not(" + ignore_key_elms + ")").empty().remove();
                $("html").animate({"scrollTop": 0}, "fast");
            },
            complete: function () {

            },
            success: function (a) {
                $("#content").css({"opacity": "0.0"}).html(a).delay(50).animate({"opacity": "1.0"}, 300)
            },
            error: function (c, d, e, f) {
                $("#content").html('<h4 class="ajax-loading-error"><i class="fa fa-warning txt-color-orangeDark"></i> 页面错误 <span class="txt-color-red">' + url + "</span>: " + c.status + ' <span style="text-transform: capitalize;">' + e + "</span></h4>")
            }
        });
    },
    delRecord: function (title, url, table) {
        let cc = $c.confirm(title, function () {
            $.ajax({
                type: "GET",
                url: url,
                dataType: "json",
                success: function (d) {
                    if (d.code == 200) {
                        table.DataTable().ajax.reload();
                    }
                    layer.close(cc);
                    $c.notify(d.msg);
                }
            });
        });
    }
};
$(window).resize(function () {
    var wHeight = $(window).height();
    var formHeight = wHeight - 250;
    $('.layui-layer').find(".form-content").css({'max-height': formHeight});
    var layerHeight = $('.layui-layer').height() + 100;
    var layerTop = (wHeight - layerHeight) / 2;
    $('.layui-layer').css({top: layerTop});
});
$.fn.extend({
    /**
     * 表单验证方法
     * @param options 验证参数
     * @example $(formName).cValidate({options})
     */
    cValidate: function (options, successFunction) {
        var defaults = {
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
        }
        var settings = $.extend(defaults, options);
        this.bootstrapValidator(settings).on('success.form.bv', function (e) {//点击提交之后
            // Prevent form submission
            e.preventDefault();

            // Get the form instance
            var $form = $(e.target);

            // Get the BootstrapValidator instance
            var bv = $form.data('bootstrapValidator');
            successFunction($form);
            /*
             // Use Ajax to submit form data 提交至form标签中的action，result自定义
             $.post($form.attr('action'), $form.serialize(), function (result) {
             //do something...
             });
             */
        });

    }
});

function date2String(time) {
    var timeString;
    time = time.replace(/T/g, " ");
    time = time.replace(/Z/g, "");
    time = time.replace(/\.\d{3}/g, "");
    timeString = time.replace(/-/g, "/");//替换字符，变成标准格式
    return timeString;
}
